package Test.负载均衡;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinDemo {
    // 定义一个全局计数器，每次调用时递增
    private static AtomicInteger index = new AtomicInteger(-1);
    // 定义一个服务器列表
    private static List<String> serverList = new ArrayList<>();
 
    public static String roundRobin() {
        // 获取服务器数量
        int serverCount = serverList.size();
        // 确定当前请求应转发到哪个服务器
        int currentServerIndex = index.incrementAndGet() % serverCount;
        // 返回相应的服务器地址
        return serverList.get(currentServerIndex);
    }
 
    public static void main(String[] args) {
        serverList.add("Server A");
        serverList.add("Server B");
        serverList.add("Server C");
        System.out.println(roundRobin());
        System.out.println(roundRobin());
        System.out.println(roundRobin());
        System.out.println(roundRobin());
    }
}